<template>
  <div>
    <!-- 导航 -->
    <van-nav-bar
      class="nav"
      title="个人信息"
      left-arrow
      @click-left="$router.back()"
    />

    <!-- 用户信息 -->

    <!-- 头像 -->
    <van-cell title="头像" is-link @click="$refs.file.click()">
      <van-image round width="0.8rem" height="0.8rem" :src="user.photo" />
      <!-- 上传文件 -->
      <input type="file" hidden ref="file" @change="selectPhoto" />
    </van-cell>
    <!-- 头像的弹层 -->
    <van-popup
      class="avator-popup"
      v-model="isShowAvator"
      :style="{ height: '100%', width: '100%' }"
      closeable
    >
      <!--动态控制弹层的创建销毁  可以在每次开启弹层时跟随图片显示裁剪框  -->
      <UpdataAvator
        :photo="photo"
        v-if="isShowAvator"
        @update-avator="updatePhoto"
      ></UpdataAvator>
    </van-popup>

    <!-- 昵称 -->
    <van-cell
      title="昵称"
      :value="user.name"
      is-link
      @click="isShowName = true"
    />
    <!-- 昵称的弹层 -->
    <van-popup
      v-model="isShowName"
      position="bottom"
      :style="{ height: '100%', width: '100%' }"
    >
      <!-- 输入框 -->
      <van-nav-bar
        title="更新昵称"
        left-text="取消"
        right-text="保存"
        left-arrow
        @click-left="cancelName"
        @click-right="updateName"
      />
      <van-field
        v-model="nickname"
        rows="2"
        autosize
        type="textarea"
        maxlength="11"
        placeholder="请输入新的昵称"
        show-word-limit
      />
    </van-popup>

    <!-- 性别 -->
    <van-cell
      title="性别"
      :value="user.gender ? '女' : '男'"
      is-link
      @click="isShowGender = true"
    />
    <!-- 性别的弹层 -->
    <van-popup v-model="isShowGender" position="bottom">
      <van-picker
        title="更新性别"
        show-toolbar
        :default-index="user.gender"
        :columns="gender"
        @confirm="updateGender"
        @cancel="isShowGender = false"
      />
    </van-popup>

    <!-- 生日 -->
    <van-cell
      title="生日"
      v-model="user.birthday"
      is-link
      @click="isShowDate = true"
    />
    <!-- 生日的弹层 -->
    <van-popup v-model="isShowDate" position="bottom">
      <van-datetime-picker
        ref="date"
        v-model="currentDate"
        title="选择年月日"
        type="date"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="updateDate"
        @cancel="isShowDate = false"
      />
    </van-popup>
  </div>
</template>

<script>
// 引入moment
import moment from 'moment'
import { getUserInfoAPI, editUserInfoAPI } from '@/api'
import UpdataAvator from './components/UpdataAvator.vue'
import { resolveToBase64 } from '@/utils'
export default {
  name: 'User',
  components: { UpdataAvator },
  data() {
    return {
      user: {},
      isShowAvator: false,
      photo: '',
      isShowName: false,
      isShowGender: false,
      gender: ['男', '女'],
      isShowDate: false,
      minDate: new Date(1900, 0, 1),
      maxDate: new Date(2022, 8, 7),
      nickname: '',
      currentDate: ''
    }
  },
  created() {
    this.getUserInfo()
  },
  watch: {
    user: {
      deep: true,
      handler(value) {
        this.$store.commit('SET_USER', value)
      }
    }
  },
  methods: {
    // 获取用户信息
    async getUserInfo() {
      try {
        const { data } = await getUserInfoAPI()
        // console.log(data)
        this.user = data.data
        this.nickname = this.user.name
        // console.log(this.user)
        const a = this.user.birthday.split('-')
        // console.log(a)
        this.currentDate = new Date(...a)
      } catch (error) {
        this.$toast.fail('获取用户信息失败，请刷新')
      }
    },
    // 用户选择了图片
    async selectPhoto(e) {
      // 1.获取用户选择的图片文件对象
      const file = e.target.files[0]
      console.dir(e.target)

      // 2.将文件对象处理成img标签可识别的url
      // 第一种方法有内存泄漏
      // const url = window.URL.createObjectURL(file)

      // 第二种优化的方法解析文件对象路径
      const url = await resolveToBase64(file)

      // 3.传给url
      this.photo = url

      // 4.清空value   以免选择相同的图片change事件不触发
      e.target.value = ''

      // 展示弹层
      this.isShowAvator = true
    },
    // 更新头像
    updatePhoto(e) {
      console.log(e)
      // 拿子组件的值修改头像
      this.user.photo = e
      // 关闭弹层
      this.isShowAvator = false
    },
    // 昵称变更
    async updateName() {
      this.$toast.loading({
        message: '修改中...',
        forbidClick: true
      })
      try {
        // 1.发请求修改服务器上的昵称
        // 2.修改页面的昵称
        await editUserInfoAPI({
          name: this.user.name
        })
        // console.log(data)
        this.user.name = this.nickname
        this.$toast.success('修改昵称成功')
      } catch (error) {
        this.$toast.fail('修改昵称失败')
      }
      // 3.关闭弹层
      this.isShowName = false
    },
    // 昵称取消变更
    cancelName() {
      this.nickname = this.user.name
      this.isShowName = false
    },
    // 性别变更
    async updateGender(value, index) {
      // console.log(`当前值：${value}, 当前索引：${index}`)
      this.$toast.loading({
        message: '修改中...',
        forbidClick: true
      })
      try {
        // 1.发请求修改服务器上的性别
        await editUserInfoAPI({
          gender: index
        })
        // console.log(data)
        // 2.修改页面的性别
        this.user.gender = index
        this.$toast.success('修改性别成功')
      } catch (error) {
        this.$toast.fail('修改性别失败')
      }
      // 3.关闭弹层
      this.isShowGender = false
    },
    // 生日变更
    async updateDate(value) {
      // console.log(value)
      this.$toast.loading({
        message: '修改中...',
        forbidClick: true
      })
      try {
        // 1.发请求修改服务器上的生日
        const newBirth = moment(value).format('YYYY-MM-DD')
        await editUserInfoAPI({
          birthday: newBirth
        })
        // console.log(data)
        // 2.修改页面的生日
        this.user.birthday = newBirth
        this.$toast.success('修改生日成功')
      } catch (error) {
        this.$toast.fail('修改生日失败')
      }
      // 3.关闭弹层
      this.isShowDate = false
    }
  }
}
</script>

<style scoped lang="less">
:deep(.nav) {
  background: #3296fa;
  .van-nav-bar__title {
    color: #fff;
  }
  .van-icon {
    color: #fff;
  }
}
.avator-popup {
  background: #000;
}
</style>
